#!/bin/sh
USBPATH=/var/mnt/usbstate/front/
PROCNAME="servicemgr"
PROCID=-1
DURING=300
SAMRATE=299

usage()
{
    echo "genperf.sh usage:"
    # echo "genperf.sh <usbpath> [procname] [during] [sample_rate]"
    echo "genperf.sh [procname] [during] [sample_rate]"
    # echo "    usbpath  : Udisk mount path, such as /var/mnt/usbstate/front/"
    echo "    procname : process name to test, default is servicemgr"
    echo "    during   : test during time, default is 300 seconds"
    echo "    sample   : test during time, default is 1999"
}

CheckArgs()
{
    if [ $# -lt 1 ]
    then
        echo "miss argument"
        usage
        exit -1
    fi
}

ParseArgs()
{
    # if [ $# -gt 0 ]
    # then
    #     USBPATH=$1
    # fi
    if [ $# -gt 0 ]
    then
        PROCNAME=$1
    fi
    if [ $# -gt 1 ]
    then
        DURING=$2
    fi
    if [ $# -gt 2 ]
    then
        SAMRATE=$3
    fi

    PROCID=$(ps | grep ${PROCNAME} | grep -v grep | grep -v  gen_ | awk '{print $1}')
    echo "USBPATH=${USBPATH}"
    echo "PROCNAME=${PROCNAME}"
    echo "DURING=${DURING}"
    echo "SAMRATE=${SAMRATE}"
    echo "PROCID=${PROCID}"

    echo "complete"
    if [ "x${PROCID}" == "x" ]
    then
        echo "process name : ${PROCNAME} is invalid"
        exit -2
    fi
    # exit 0
}

GetUSBPath()
{
    mountinfo=$(df | grep usbstate)
    if [ "x${mountinfo}" == "x"  ]
    then
        echo "get usb path fail,insert  Udisk first"
        exit -3
    fi
    USBPATH=$(echo ${mountinfo}| awk '{print $6}')
    echo "USBPATH:${USBPATH}"
}

# CheckUsbExist()
# {
#     exsit=$(df | grep "${USBPATH}")
#     if [ "x${exsit}" == "x"  ]
#     then
#         echo "USB path: ${USBPATH} is NOT the USB mount path"
#         exit -3
#     fi
# }

main()
{
    CheckArgs $@
    GetUSBPath
    ParseArgs $@
    # CheckUsbExist

    cd ${USBPATH}
    if [  -d "perf_data" ]
    then
        rm -rf perf_data
    fi
    mkdir perf_data

    cd perf_data
    echo ${SAMRATE} > /proc/sys/kernel/perf_event_max_sample_rate
    perf record -g -p ${PROCID} -F ${SAMRATE}  -a -- sleep ${DURING}
    # sleep ${SAMRATE}
    # perf record -g -p ${PROCID} -F ${SAMRATE}  -a -- sleep ${DURING}

    # sleep ${DURING}
    # killall -9 perf

    perf report --sort=cpu > log_cpu.txt
    perf report --sort=overhead > log_overhead.txt
    perf report --sort=overhead_sys > log_kernel.txt
    perf report --sort=overhead_us > log_user.txt
    perf report --sort=sample > log_sample.txt
    perf script -i perf.data  > perf.unfold
    cd /
    # umount -l ${USBPATH}
    echo "perf file complete"
}

main $@
